package com.zyf.school.manager.controller;

import com.zyf.school.manager.domain.Department;
import com.zyf.school.manager.domain.DepartmentTree;
import com.zyf.school.manager.domain.Tree;
import com.zyf.school.manager.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/department/")

public class DepartmentController {

    @Autowired
    DepartmentService departmentService;

    List<Department> departmentList;
    //list
    @RequestMapping("list")
    public String list(HttpServletRequest request){
        departmentList = departmentService.queryAll();
        request.setAttribute("departmentList",departmentList);
        List<Tree> treeList = new ArrayList<>();
        treeList = DepartmentTree.toTree(treeList,departmentList);
        request.setAttribute("departmentTreeList", treeList);
        return "/department/list";
    }
    @RequestMapping("queryParent")
    public String queryParent(HttpServletRequest request,@RequestParam("id") int id){
        departmentList = departmentService.queryParent(id);
        request.setAttribute("departmentList",departmentList);
        List<Tree> treeList = new ArrayList<>();
        departmentList = departmentService.queryAll();
        treeList = DepartmentTree.toTree(treeList,departmentList);
        request.setAttribute("departmentTreeList", treeList);
        return "/department/list";
    }
    //添加子部门
    @RequestMapping("add")
    public String add(HttpServletRequest request,@RequestParam("id") int id){
        Department department = departmentService.queryById(id);
        request.setAttribute("department",department);
        List<Tree> treeList = new ArrayList<>();
        departmentList = departmentService.queryAll();
        treeList = DepartmentTree.toTree(treeList,departmentList);
        request.setAttribute("departmentTreeList", treeList);
        return "/department/add";
    }

    //保存数据
    @RequestMapping("save")
    public String save(HttpServletRequest request,Department department){
        departmentService.save(department);
        return this.list(request);
    }
}
